<template>
  <div class="profile-container">
    <div class="profile-header">
      <h2>个人中心</h2>
      <p>管理您的个人信息和账户设置</p>
    </div>

    <div class="profile-content">
      <!-- 用户信息卡片 -->
      <div class="info-card">
        <div class="card-header">
          <h3>基本信息</h3>
          <button @click="toggleEdit" class="edit-btn">
            {{ isEditing ? '取消编辑' : '编辑信息' }}
          </button>
        </div>

        <div class="user-avatar">
          <div class="avatar-placeholder">
            {{ userInfo.realName ? userInfo.realName.charAt(0) : (userInfo.username ? userInfo.username.charAt(0) : 'U')
            }}
          </div>
        </div>

        <form v-if="isEditing" @submit.prevent="updateProfile" class="profile-form">
          <div class="form-group">
            <label>用户名</label>
            <input type="text" :value="userInfo.username" disabled />
            <small>用户名不可修改</small>
          </div>

          <div class="form-group">
            <label>邮箱</label>
            <input type="email" :value="userInfo.email" disabled />
            <small>邮箱不可修改</small>
          </div>

          <div class="form-group">
            <label>真实姓名</label>
            <input v-model="editForm.realName" type="text" placeholder="请输入真实姓名" />
          </div>

          <div class="form-group">
            <label>手机号</label>
            <input v-model="editForm.phone" type="tel" placeholder="请输入手机号" />
          </div>

          <div class="form-actions">
            <button type="submit" class="save-btn" :disabled="loading">
              {{ loading ? '保存中...' : '保存' }}
            </button>
            <button type="button" @click="cancelEdit" class="cancel-btn">
              取消
            </button>
          </div>
        </form>

        <div v-else class="info-display">
          <div class="info-item">
            <label>用户名</label>
            <span>{{ userInfo.username }}</span>
          </div>

          <div class="info-item">
            <label>邮箱</label>
            <span>{{ userInfo.email }}</span>
          </div>

          <div class="info-item">
            <label>真实姓名</label>
            <span>{{ userInfo.realName || '未设置' }}</span>
          </div>

          <div class="info-item">
            <label>手机号</label>
            <span>{{ userInfo.phone || '未设置' }}</span>
          </div>

          <div class="info-item">
            <label>角色</label>
            <span class="role-badge" :class="userInfo.role ? userInfo.role.toLowerCase() : 'user'">
              {{ userInfo.role === 'ADMIN' ? '管理员' : '普通用户' }}
            </span>
          </div>

          <div class="info-item">
            <label>状态</label>
            <span class="status-badge" :class="{ active: userInfo.status }">
              {{ userInfo.status ? '正常' : '禁用' }}
            </span>
          </div>

          <div class="info-item">
            <label>注册时间</label>
            <span>{{ formatDate(userInfo.createTime) }}</span>
          </div>

          <div class="info-item">
            <label>最后登录</label>
            <span>{{ userInfo.lastLoginTime ? formatDate(userInfo.lastLoginTime) : '从未登录' }}</span>
          </div>
        </div>
      </div>

      <!-- 密码修改卡片 -->
      <div class="info-card">
        <div class="card-header">
          <h3>修改密码</h3>
        </div>

        <form @submit.prevent="changePassword" class="password-form">
          <div class="form-group">
            <label>当前密码</label>
            <input v-model="passwordForm.oldPassword" type="password" placeholder="请输入当前密码" required />
          </div>

          <div class="form-group">
            <label>新密码</label>
            <input v-model="passwordForm.newPassword" type="password" placeholder="请输入新密码（至少6位）" required />
          </div>

          <div class="form-group">
            <label>确认新密码</label>
            <input v-model="passwordForm.confirmPassword" type="password" placeholder="请再次输入新密码" required />
          </div>

          <button type="submit" class="change-password-btn" :disabled="passwordLoading">
            {{ passwordLoading ? '修改中...' : '修改密码' }}
          </button>
        </form>
      </div>

      <!-- 账户操作卡片 -->
      <div class="info-card">
        <div class="card-header">
          <h3>账户操作</h3>
        </div>

        <div class="account-actions">
          <button @click="logout" class="logout-btn">
            退出登录
          </button>
        </div>
      </div>
    </div>

    <!-- 消息提示 -->
    <div v-if="message" class="message" :class="messageType">
      {{ message }}
    </div>
  </div>
</template>

<script>
import { authAPI } from '@/api/auth'

export default {
  name: 'Profile',
  data() {
    return {
      userInfo: {},
      isEditing: false,
      loading: false,
      passwordLoading: false,
      message: '',
      messageType: 'success',
      editForm: {
        realName: '',
        phone: ''
      },
      passwordForm: {
        oldPassword: '',
        newPassword: '',
        confirmPassword: ''
      }
    }
  },
  async mounted() {
    await this.loadUserInfo()
  },
  methods: {
    // 加载用户信息
    async loadUserInfo() {
      try {
        const response = await authAPI.getUserInfo()
        this.userInfo = response.data.userInfo
        this.editForm.realName = this.userInfo.realName || ''
        this.editForm.phone = this.userInfo.phone || ''
      } catch (error) {
        console.error('获取用户信息失败:', error)
        this.showMessage('获取用户信息失败', 'error')
      }
    },

    // 切换编辑模式
    toggleEdit() {
      this.isEditing = !this.isEditing
      if (this.isEditing) {
        this.editForm.realName = this.userInfo.realName || ''
        this.editForm.phone = this.userInfo.phone || ''
      }
    },

    // 取消编辑
    cancelEdit() {
      this.isEditing = false
      this.editForm.realName = this.userInfo.realName || ''
      this.editForm.phone = this.userInfo.phone || ''
    },

    // 更新用户信息
    async updateProfile() {
      this.loading = true
      try {
        const response = await authAPI.updateProfile(this.editForm)
        this.userInfo = response.data.userInfo
        this.isEditing = false
        this.showMessage('用户信息更新成功', 'success')

        // 更新本地存储的用户信息
        localStorage.setItem('userInfo', JSON.stringify(this.userInfo))
      } catch (error) {
        console.error('更新用户信息失败:', error)
        this.showMessage(error.response?.data?.message || '更新失败', 'error')
      } finally {
        this.loading = false
      }
    },

    // 修改密码
    async changePassword() {
      if (this.passwordForm.newPassword !== this.passwordForm.confirmPassword) {
        this.showMessage('两次输入的新密码不一致', 'error')
        return
      }

      if (this.passwordForm.newPassword.length < 6) {
        this.showMessage('新密码长度不能少于6位', 'error')
        return
      }

      this.passwordLoading = true
      try {
        await authAPI.changePassword({
          oldPassword: this.passwordForm.oldPassword,
          newPassword: this.passwordForm.newPassword
        })

        this.showMessage('密码修改成功', 'success')
        this.passwordForm = {
          oldPassword: '',
          newPassword: '',
          confirmPassword: ''
        }
      } catch (error) {
        console.error('修改密码失败:', error)
        this.showMessage(error.response?.data?.message || '修改密码失败', 'error')
      } finally {
        this.passwordLoading = false
      }
    },

    // 退出登录
    async logout() {
      if (confirm('确定要退出登录吗？')) {
        try {
          await authAPI.logout()
        } catch (error) {
          console.error('退出登录失败:', error)
        } finally {
          // 清除本地存储
          localStorage.removeItem('satoken')
          localStorage.removeItem('userInfo')
          // 跳转到登录页
          this.$router.push('/login')
        }
      }
    },

    // 显示消息
    showMessage(text, type = 'success') {
      this.message = text
      this.messageType = type
      setTimeout(() => {
        this.message = ''
      }, 3000)
    },

    // 格式化日期
    formatDate(dateString) {
      if (!dateString) return ''
      const date = new Date(dateString)
      return date.toLocaleString('zh-CN')
    }
  }
}
</script>

<style scoped>
.profile-container {
  max-width: 800px;
  margin: 0 auto;
  padding: 20px;
}

.profile-header {
  text-align: center;
  margin-bottom: 30px;
}

.profile-header h2 {
  color: #333;
  margin-bottom: 8px;
}

.profile-header p {
  color: #666;
  margin: 0;
}

.profile-content {
  display: flex;
  flex-direction: column;
  gap: 20px;
}

.info-card {
  background: white;
  border-radius: 12px;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
  padding: 24px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  padding-bottom: 12px;
  border-bottom: 1px solid #e1e5e9;
}

.card-header h3 {
  margin: 0;
  color: #333;
}

.edit-btn {
  background: #667eea;
  color: white;
  border: none;
  padding: 8px 16px;
  border-radius: 6px;
  cursor: pointer;
  font-size: 14px;
}

.edit-btn:hover {
  background: #5a6fd8;
}

.user-avatar {
  text-align: center;
  margin-bottom: 20px;
}

.avatar-placeholder {
  width: 80px;
  height: 80px;
  border-radius: 50%;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  color: white;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 32px;
  font-weight: bold;
  margin: 0 auto;
}

.profile-form,
.password-form {
  display: flex;
  flex-direction: column;
  gap: 16px;
}

.form-group {
  display: flex;
  flex-direction: column;
}

.form-group label {
  margin-bottom: 6px;
  color: #333;
  font-weight: 500;
  font-size: 14px;
}

.form-group input {
  padding: 10px 12px;
  border: 2px solid #e1e5e9;
  border-radius: 6px;
  font-size: 14px;
}

.form-group input:focus {
  outline: none;
  border-color: #667eea;
}

.form-group input:disabled {
  background: #f5f5f5;
  color: #999;
}

.form-group small {
  margin-top: 4px;
  color: #666;
  font-size: 12px;
}

.form-actions {
  display: flex;
  gap: 12px;
  margin-top: 8px;
}

.save-btn,
.change-password-btn {
  background: #667eea;
  color: white;
  border: none;
  padding: 10px 20px;
  border-radius: 6px;
  cursor: pointer;
  font-size: 14px;
}

.save-btn:hover,
.change-password-btn:hover {
  background: #5a6fd8;
}

.cancel-btn {
  background: #6c757d;
  color: white;
  border: none;
  padding: 10px 20px;
  border-radius: 6px;
  cursor: pointer;
  font-size: 14px;
}

.cancel-btn:hover {
  background: #5a6268;
}

.info-display {
  display: flex;
  flex-direction: column;
  gap: 16px;
}

.info-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 12px 0;
  border-bottom: 1px solid #f0f0f0;
}

.info-item:last-child {
  border-bottom: none;
}

.info-item label {
  font-weight: 500;
  color: #666;
  min-width: 100px;
}

.info-item span {
  color: #333;
}

.role-badge {
  padding: 4px 12px;
  border-radius: 20px;
  font-size: 12px;
  font-weight: 500;
}

.role-badge.admin {
  background: #fee;
  color: #c33;
}

.role-badge.user {
  background: #efe;
  color: #363;
}

.status-badge {
  padding: 4px 12px;
  border-radius: 20px;
  font-size: 12px;
  font-weight: 500;
}

.status-badge.active {
  background: #efe;
  color: #363;
}

.status-badge:not(.active) {
  background: #fee;
  color: #c33;
}

.account-actions {
  display: flex;
  gap: 12px;
}

.logout-btn {
  background: #dc3545;
  color: white;
  border: none;
  padding: 10px 20px;
  border-radius: 6px;
  cursor: pointer;
  font-size: 14px;
}

.logout-btn:hover {
  background: #c82333;
}

.message {
  position: fixed;
  top: 20px;
  right: 20px;
  padding: 12px 20px;
  border-radius: 6px;
  font-size: 14px;
  z-index: 1000;
}

.message.success {
  background: #efe;
  color: #363;
  border: 1px solid #cfc;
}

.message.error {
  background: #fee;
  color: #c33;
  border: 1px solid #fcc;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .profile-container {
    padding: 15px;
  }

  .info-card {
    padding: 20px 16px;
  }

  .card-header {
    flex-direction: column;
    gap: 12px;
    align-items: flex-start;
  }

  .info-item {
    flex-direction: column;
    align-items: flex-start;
    gap: 4px;
  }

  .form-actions {
    flex-direction: column;
  }
}
</style>